from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from forms import MessageForm
from models import Message

def message(request):
    if request.method == 'POST':
        form = MessageForm(request.POST,request.FILES)
        if form.is_valid():
            name = form.cleaned_data['name']
            content = form.cleaned_data['content']
            ip = request.META['REMOTE_ADDR']
            imagefile = form.cleaned_data['imagefile']
            savefile = form.cleaned_data['savefile']
            m = Message(name=name,
                        content=content,
                        imagefile=imagefile,
                        savefile=savefile,
                        ip=ip
                        )
            m.save()
            return HttpResponseRedirect('/guestbook/')
    else:
        form = MessageForm()
    messages = Message.objects.all().order_by('-time')
    return render_to_response('guestbook.html',{'form': form, 'messages': messages})